package com.woniu.publisher;

import com.woniu.util.ConstantUtil;
import org.springframework.amqp.core.ReturnedMessage;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class ProductPublisher implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnsCallback{
    @Resource
    private RabbitTemplate rabbitTemplate;
    public void send(String msg,Integer ttl) {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnsCallback(this);
        rabbitTemplate.convertAndSend(ConstantUtil.RABBIT_EXCHANGE,
                "product",
                msg,
                message -> {
                    message.getMessageProperties().setDelay(ttl);
                    return message;
                }
        );
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean b, String s) {
        if (!b) {
            System.out.println("消息补偿");
        }
    }

    @Override
    public void returnedMessage(ReturnedMessage returnedMessage) {
        System.out.println(returnedMessage.getMessage());
    }
}
